package com.gopay.checkorder.service.task.thread;

import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.checkorder.service.BankOrderService;
import com.gopay.checkorder.service.alarm.OrderAlarmDataCollector;
import com.gopay.common.constants.bank.BankOrderStatus;
import com.gopay.common.domain.bank.BankOrder;
import com.gopay.common.domain.cps.vo.CheckOrderResult;

/**
 * 对单线程类
 * 
 * @CheckOrderThread.java
 * @author fanghw
 * @2016年1月7日 下午2:24:52 www.gopay.com.cn Inc.All rights reserved.
 */
public class CheckOrderThread implements Runnable {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private BankOrderService bankOrderService;
    private ConcurrentLinkedQueue<BankOrder> queue;
    private CountDownLatch latch;
    
    private OrderAlarmDataCollector alarmCollector;

    public CheckOrderThread(BankOrderService bankOrderService, ConcurrentLinkedQueue<BankOrder> queue,
            CountDownLatch latch,OrderAlarmDataCollector alarmCollector) {
        this.bankOrderService = bankOrderService;
        this.queue = queue;
        this.latch = latch;
        this.alarmCollector=alarmCollector;
    }

    @Override
    public void run() {
        BankOrder bankOrder = null;
        while ((bankOrder = queue.poll()) != null) {
            try {
                alarmCollector.addTotal(bankOrder.getBankCode());
                
                CheckOrderResult checkResult=bankOrderService.checkOrder(bankOrder, BankOrderStatus.AUTO_CHECK_SUCCESS);
                if(checkResult!=null && checkResult.isCommunicateError()==true){
                    logger.error("checkResult  communicateError-----------"+checkResult.isCommunicateError());
                    alarmCollector.addFail(bankOrder.getBankCode());
                    logger.error("checkResult  fail*****"+alarmCollector.getFail(bankOrder.getBankCode()));
                    logger.error("checkResult  total****"+alarmCollector.getTotal(bankOrder.getBankCode()));
                }
                
                logger.info("**********************当前队列剩余订单数：" + queue.size());
            } catch (Exception e) {
                logger.info("---------- 对单error---------", e);
            } finally {
                latch.countDown();
            }
        }
    }

}
